"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.broadcastRouter = void 0;
const express_1 = __importDefault(require("express"));
const log4js_1 = require("log4js");
const create_1 = require("../../webrtc/create");
const Classrooms_1 = require("../../lib/Classrooms");
const Member_1 = require("../../lib/Member");
const logger = (0, log4js_1.getLogger)('route/broadcast');
function broadcastRouter(app) {
    const router = express_1.default.Router();
    router.post('/uri', async ({ body }, res) => {
        var _a;
        const { intercom, clientUtils } = app.locals;
        logger.debug('broadcast uri: ' + JSON.stringify(body, null, 2));
        const { uri, room, members, owner } = body;
        const configuration = (_a = body.configuration) !== null && _a !== void 0 ? _a : { audio: true, video: true };
        const roomOptions = {
            ...room,
            chatMode: 'BROADCAST',
            inviteMode: 'NO_VERIFY',
            joinMode: 'NO_VERIFY',
            conferenceMode: 'DEFAULT',
            classType: 'TEMPORARY',
            mediaOptions: { configuration }
        };
        let dbChat;
        try {
            const classroom = (0, create_1.createClassroom)(roomOptions, owner, members, { configuration });
            const __owner = Member_1.Member.proxy(owner, intercom);
            const options = {
                room: classroom.json(),
                creator: owner,
                members,
                mediaOptions: { configuration }
            };
            classroom.client = await clientUtils.getClient();
            classroom.pipeline = await clientUtils.createMediaPipeline(classroom.client);
            __owner.player = await clientUtils.createPlayerEndpoint(classroom.pipeline, uri);
            __owner.player.getStats((error, stats) => {
                console.log('player.getStats: => ', error);
                if (error)
                    return;
                console.log('stats: => ', stats);
            });
            __owner.player.on('EndOfStream', function (data, data2) {
                const __classroom = Classrooms_1.Classrooms.get(classroom.classId);
                console.log('EndOfStream: => ', data, data2);
                __classroom.getMembers().forEach(member => {
                    var _a;
                    member.stop(room.classId);
                    (_a = intercom[member.userId]) === null || _a === void 0 ? void 0 : _a.emit('dissolve', { room, destroyer: owner });
                });
                __classroom.destroy();
            });
            classroom.setMember(__owner);
            Classrooms_1.Classrooms.set(classroom.classId, classroom);
            members.forEach(({ userId }) => {
                var _a;
                if ((_a = intercom[userId]) === null || _a === void 0 ? void 0 : _a.emit) {
                    setTimeout(() => {
                        intercom[userId].emit('invite', options, () => { });
                    }, 400);
                }
            });
            res.status(200).send({ result: 'OK', data: dbChat });
        }
        catch (error) {
            logger.debug(error);
            res.status(200).send({ result: 'Error', message: error });
        }
    });
    return router;
}
exports.broadcastRouter = broadcastRouter;
